<template>
  <div class="apply-settle">
    <el-row class="info-div" style="padding: 30px">
      <el-steps :active="step - 1" finish-status="success" style="padding:20px 50px 0 50px">
        <el-step title="个人信息" icon="el-icon-edit-outline"></el-step>
        <el-step title="选择学术成果" icon="el-icon-folder-add"></el-step>
        <el-step title="完成" icon="el-icon-success"></el-step>
      </el-steps>

      <el-divider/>

      <el-row align="middle" justify="center" type="flex">
        <el-col align="left" style="padding: 0 50px 0 50px;">
          <!--第一步-->
          <el-row :hidden="step !== 1" style="font-size: large; width:80%;" class="block1">
            <el-row class="fill-in-row">
              <el-col :span="7" class="sub-title">
                姓名
              </el-col>
              <el-col :span="17">
                <el-input v-model="applyInfo.author_name" placeholder="请输入姓名"></el-input>
              </el-col>
            </el-row>
            <el-row class="fill-in-row">
              <el-col :span="7" class="sub-title">
                职位
              </el-col>
              <el-col :span="17">
                <el-input v-model="applyInfo.affiliation_name" placeholder="请输入职位"></el-input>
              </el-col>
            </el-row>

            <el-row class="fill-in-row">
              <el-col :span="7" class="sub-title">
                机构
              </el-col>
              <el-col :span="17">
                <el-input v-model="applyInfo.workplace" placeholder="请输入机构名称"></el-input>
              </el-col>
            </el-row>

            <el-row class="fill-in-row">
              <el-col :span="7" class="sub-title">
                研究领域
              </el-col>
              <el-col :span="17">
                <!-- <el-input v-model="applyInfo.fields" placeholder="多个研究领域用英文半角逗号分隔"></el-input> -->
                <el-input v-model="applyInfo.fields" placeholder="请输入研究领域"></el-input>
              </el-col>
            </el-row>

            <!-- <el-row class="fill-in-row">
              <el-col :span="7" class="sub-title">
                个人首页（可选）
              </el-col>
              <el-col :span="17">
                <el-input v-model="applyInfo.home_page" placeholder="请输入您的个人首页"></el-input>
              </el-col>
            </el-row> -->
            <div class="button11">
            <el-button style="margin-top: 20px; margin-left: 240px" type="primary" @click="submit_info"> 下一步</el-button>
          </div>
          </el-row>
          <!--  第一步结束    -->

          <!--      第二步开始-->
          <!-- <el-row :hidden="step !== 2">
            <el-row justify="space-around" style="padding-bottom: 10px; width: 100%; " type="flex">
              <el-col style="text-align: left">已根据您的姓名，检索出 <span
                  style="font-weight: 600; color: #217ad9; font-size: x-large; ">{{ author_count }}</span>
                个文章组，请选择：
              </el-col>
              <el-col>
                <el-row justify="end" style="padding-right: 5px;" type="flex">
                  <el-button type="primary" @click="confirm_choice"> 确认</el-button>
                </el-row>
              </el-col>
            </el-row>
            <el-row>
              <el-collapse v-model="opened_collapse" class="papers-collapse" accordion>
                <el-collapse-item v-for="(papers, index) in authors" :key="index"
                                  :name="papers.author_id">
                  <template slot="title">
                    <el-checkbox v-model="papers_group_state[index].selected" class="choose-paper-checkbox"
                                 style="padding-left: 20px">
                      <span style="font-size: 17px;margin: 10px;font-weight: bold; color: #2f2e2e"
                            v-bind="papers_group_state[index].selected">
                      {{ papers.name }}
                      </span>
                    </el-checkbox>
                  </template>
                  <div v-for="(item, index) in papers.papers" v-bind:key="index" class="article-item" style="margin-left: 60px; margin-top: 10px; color: grey;">
                    <div v-if="index<6" style="text-align: left">
                      <div style="margin-bottom: 5px">
                        <span class="paper-title"
                              style="font-size: 16px; font-family:'Times Roman',sans-serif ;color: rgba(53,53,53,0.94)"
                              @click="gotoArticle(item.paper_id)">
                          {{ index+1 }}. {{ item.paper_title }}</span>
                      </div>
                      <span v-for="(j, index) in item.authors" :key="j">
                        {{ j.author_name }}
                        <span v-if="index<item.authors.length-1"> / </span>
                      </span>
                      <span> · {{ item.year }}</span>
                      <span> · {{ item.publisher }} </span>
                    </div>
                  </div>
                  <div
                      v-if="papers.papers.length>6"
                      style="margin-left: 60px; margin-top: 10px; color: grey; text-align: left; color: rgba(53,53,53,0.94)"
                      class="paper-title">
                    ···
                  </div>
                </el-collapse-item>
              </el-collapse>
              <scroll-loader :loader-method="getArticlesByAuthor" :loader-disable="loadMoreDisable"></scroll-loader>
            </el-row>
          </el-row> -->
          
          <!--step2  -->
          <el-row :gutter="0" v-if="this.author_count!==0" :hidden="step !== 2" class="block2">
            <!-- <el-col :span="7"><div class="grid-content bg-purple" style="margin-right:50px">
              <span style="display:flex; margin-bottom:24px; margin-top:10px; font-size:16px; color: #A0A0A0">筛选</span>
              <el-card class="box-card">
                <div class="author-affiliation sub-block">
                  <div class="check-box-title">
                    <span>机构</span>
                  </div>
                  <el-checkbox-group v-for="o in aggregation.affiliations"
                                     :key="o"
                                     style="margin-bottom: 15px; text-align: left"
                                     @change="getAuthorRes"
                                     v-model="checkAffiliationList">
                    <el-checkbox :label=o.name>
                      <el-tooltip class="item" effect="dark" :content="o.name" placement="right">
                        <span>{{ o.name|ellipsis_30 }}&nbsp;({{ o.count }})</span>
                      </el-tooltip>
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
  
              </el-card>
            </div>
            </el-col> -->
  
            <el-col :span="16"><div class="grid-content bg-purple">
              <!-- <div>
                <el-row>
                  <el-col span="17">
                    <span style="display:flex; font-size:16px; margin-top:10px;color: #A0A0A0">学者 ({{ total_hits_str }})</span>
                  </el-col>
                  <el-col span="2">
                    <div style="margin-top:10px">
                      <span style="font-size:16px;color: #A0A0A0">排序</span>
                    </div>
                  </el-col>
                  <el-col span="5">
                    <el-select v-model="sortValue"
                               placeholder="请选择"
                               style="float:right; height:30px; margin-bottom:5px"
                               @change="getAuthorRes">
                      <el-option
                          v-for="item in queue"
                          :key="item"
                          :label="item.label"
                          :value="item.value">
                      </el-option>
                    </el-select>
                  </el-col>
                </el-row>
              </div> -->
              
              <AuthorBlocks
                  :authors="authors"
                  :author_avatars="author_avatars"
              ></AuthorBlocks>
  
              <div class="buttons">
                <el-button style="margin-top: 20px; margin-left: 240px" type="primary" @click="returnback"> 上一步</el-button>
              <el-button style="margin-top: 20px; margin-left: 10px" type="primary" @click="secondClick"> 下一步</el-button>
            </div>
            </div></el-col>
          </el-row>
          <el-empty :image-size="200" description="暂无相关学者数据" v-else></el-empty>

          <!--step 3 start -->
          <el-row :hidden="step !== 3" class="block3">
            <el-col>
              <el-result icon="success"  title="">
                <template slot="title">
                  <span style="font-size: large">欢迎入驻</span>
                </template>
                <template slot="subTitle">
                  <span style="font-size: 16px">您的申请将在3天内由管理员审核，请耐心等待</span>
                </template>
                <template slot="extra">
                  <el-button type="primary" @click="gotoHome">返回</el-button>
                </template>
              </el-result>
            </el-col>
            <!--step 3 ended-->
          </el-row>
        </el-col>
      </el-row>
    </el-row>
  </div>
</template>

<script>

import qs from "qs";
import user from "../../store/user";
import AuthorBlocks from "../../components/AuthorBlocks3";

export default {
  name: "ApplySettle",
  components: {AuthorBlocks},
  data() {
    var checkauthorname = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('姓名不能为空'));
        } 
      };
      var checkaffiliation_name = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('职位不能为空'));
        } 
      };
      var checkfields = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('领域不能为空'));
        } 
      };
      var checkworkplace = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('机构不能为空'));
        } 
      };
    return {
      bindID:'',
      count: 0,
      step: 1,
      applyInfo: {
        author_name: "",
        affiliation_name: "",
        // work_email: "",
        fields: "",
        workplace:"",
        // home_page: "",
        author_id: "",
      },
      rules: {
          author_name: [
            { validator: checkauthorname, trigger: 'blur'}
          ],
          affiliation_name: [
            { validator: checkaffiliation_name, trigger: 'blur'}
          ],
          fields: [
            { validator: checkfields, trigger: 'blur' }
          ],
          workplace: [
            { validator: checkworkplace, trigger: 'blur' }
          ],
        },
      papers_group_state: [
        {
          open: true,
          selected: false,
          author_id: "a123"
        },
        {
          open: true,
          selected: false,
          author_id: "a12acd3"
        }
      ],
      author_count: 10,
      author_avatars:[],
      authors: [
        // {
        //   author_id: "a123",
        //   name: "Li Yu",
        //   papers: [
        //     {
        //       "authors": [
        //         {
        //           "affiliation_id": "",
        //           "affiliation_name": "Independent Researcher",
        //           "author_id": "3192512793",
        //           "author_name": "Sergei Belousov",
        //           "order": "1"
        //         },
        //         {
        //           "affiliation_id": "",
        //           "affiliation_name": "Independent Researcher",
        //           "author_id": "3192512793",
        //           "author_name": "Sergei Belousov",
        //           "order": "1"
        //         }
        //       ],
        //       "book_title": "",
        //       "citation_count": "0",
        //       "citation_msg": [],
        //       "conference": "",
        //       "conference_id": "",
        //       "date": "2021-11-01",
        //       "doctype": "",
        //       "doi": "10.1016/J.SIMPA.2021.100115",
        //       "doi_url": "https://dx.doi.org/10.1016/J.SIMPA.2021.100115 Add to Citavi project by DOI",
        //       "fields": [],
        //       "first_page": "100115",
        //       "journal": "",
        //       "journal_id": "",
        //       "last_page": "",
        //       "paper_id": "3191610454",
        //       "paper_title": "mobilestylegan pytorch pytorch based toolkit to compress stylegan2 model",
        //       "publisher": "Elsevier BV",
        //       "rank": "23112",
        //       "reference_count": "12",
        //       "volume": "10",
        //       "year": "2021"
        //     },
        //     {
        //       "authors": [
        //         {
        //           "affiliation_id": "",
        //           "affiliation_name": "Independent Researcher",
        //           "author_id": "3192512793",
        //           "author_name": "Sergei Belousov",
        //           "order": "1"
        //         },
        //         {
        //           "affiliation_id": "",
        //           "affiliation_name": "Independent Researcher",
        //           "author_id": "3192512793",
        //           "author_name": "Sergei Belousov",
        //           "order": "1"
        //         }
        //       ],
        //       "book_title": "",
        //       "citation_count": "0",
        //       "citation_msg": [],
        //       "conference": "",
        //       "conference_id": "",
        //       "date": "2021-11-01",
        //       "doctype": "",
        //       "doi": "10.1016/J.SIMPA.2021.100115",
        //       "doi_url": "https://dx.doi.org/10.1016/J.SIMPA.2021.100115 Add to Citavi project by DOI",
        //       "fields": [],
        //       "first_page": "100115",
        //       "journal": "",
        //       "journal_id": "",
        //       "last_page": "",
        //       "paper_id": "3191610454",
        //       "paper_title": "mobilestylegan pytorch pytorch based toolkit to compress stylegan2 model",
        //       "publisher": "Elsevier BV",
        //       "rank": "23112",
        //       "reference_count": "12",
        //       "volume": "10",
        //       "year": "2021"
        //     }
        //   ]
        // },
      ],
      author_page_idx: 1,
      loadMoreDisable: true,
    }
  },
  beforeRouteEnter(to,from,next){
    if(!sessionStorage.getItem('authorId') || sessionStorage.getItem('authorId') !=='null'){
      next('/')
    }
    else next()
  },
  watch: {
    // authors(val) {
    //   this.loadMoreDisable = val.length >= this.author_count;
    // },
  },
  mounted() {
    this.$bus.$on('getBindID',this.getBindID)
    // this.$bus.$off('nowID')
    this.$bus.$on('nowID',this.getnowID)
  },
  computed: {
    opened_collapse: function () {
      return this.papers_group_state.filter((x) => x.open).map(x => x.author_id);
    }
  },
  created() {
    // const userInfo = user.getters.getUser(user.state());
    // console.log(this.bindID,"bindID111")
    // if(this.bindID!=0){
      // this.$bus.$emit('sendID',this.bindID)
      // this.secondClick();
    // }
  },
  methods: {
    getnowID(id1){
      this.bindID=id1
      console.log(this.bindID,"bindID111")
      this.secondClick();
    },

    getBindID(data){
      this.bindID=data
      console.log(this.bindID)
    },
    
    secondClick(){
      if(this.bindID=='')
      {
        this.$message.error("请选择一个绑定的学者！")
        // alert("second1")
      }
      else{
        // alert("second2")
      // this.confirm_choice()
      const formData1=new FormData();
      formData1.append("uid",this.$store.state.user.userId)
      formData1.append("uposition",this.applyInfo.affiliation_name)
      formData1.append("uname",this.applyInfo.author_name)
      formData1.append("uarea",this.applyInfo.fields)
      formData1.append("author_id",this.bindID)//待完善
      formData1.append("organization",this.applyInfo.workplace)
      this.$axios({
          method: 'POST',
          url: '/user/sendCertification/',
          // data: JSON.stringify(formData),
          data:formData1
        })
        .then(res => {
        console.log(res.data)
          // alert(res.data.content)
        if (res.data.code == 200) {
          this.step=3;
          } else if( this.bindID!=''){
            this.$message.error(res.data.msg);
          }
        })
        .catch(err => {
          console.log(err);
        })
      }
    },

    returnback(){
      this.step=1
    },
   
    // 输入姓名后 筛选出结果 第一步点击下一步触发
    submit_info() {
      // if (this.isStep1Valid()) {
      //   if (this.$route.query.v && this.$route.query.v!=='') {
      //     const userInfo = user.getters.getUser(user.state());
      //     this.applyInfo['user_id'] = userInfo.user.userId;
      //     this.applyInfo['author_id'] = this.$route.query.v;
      //     this.$notify({
      //       title: '成功',
      //       message: '由于您通过点击学者门户页面的认领按钮进入此页面，因此已自动为您选择学术成果',
      //       type: 'success'
      //     });
      //     setTimeout(() => {
      //       this.apply();
      //     }, 1000);
      //   } else {
      //     this.getArticlesByAuthor();
      //   }
      // } else {
      //   // this.$message.error("请完善必填信息！");
      //   this.step=2;
      // }
      if(this.applyInfo.author_name != "" && this.applyInfo.affiliation_name != "" && this.applyInfo.fields != "" && this.applyInfo.workplace != ""){
        this.step=2;

      const Data = {
        // affiliation_name: this.input,
        author_name: this.applyInfo.author_name,
        sort_type: 1,
        sort_ascending: 1,
        page: 1,
        size: 10,
        // affiliations: JSON.stringify(affiliations)
    };
    const Data2 = JSON.stringify(Data);
      this.$axios({
        method: 'post',
        url: '/search/SearchAut/',
        data: Data2
      })
      .then(res => {
        console.log(res.data.content)
        switch (res.data.status) {
        case 200:
            this.authors = res.data.item;
            console.log(this.authors);
            this.author_count= res.data.hits;
            // this.total_hits_str = res.data.hits.toLocaleString();
            // this.aggregation = res.data.aggregation;
            if (res.data.total_hits === 10000)
            this.author_count = "10000+";
            // 获取学者头像
            // this.getAuthorAvatars();
            break;
        }
    })
    .catch(err => {
        console.log(err);
    })
      }
      else{
        this.$message.warning("请填写全部信息")
      }
      
    },
    // 提交认证申请 第二步点击下一步触发
    confirm_choice() {
      const userInfo = user.getters.getUser(user.state());
      let userId = userInfo.user.userId;
      if (this.isStep2Valid()) {
        this.applyInfo['user_id'] = userId;
        this.apply();
      } 
    },
    apply() {
      let _loadingIns = this.$loading({fullscreen: true, text: '正在提交申请！'});
      this.$axios({
        method: 'post',
        url: '/submit/create/',
        data: qs.stringify(this.applyInfo)
      })
      .then(res => {
        _loadingIns.close();
        switch (res.data.status) {
          case 200:
            this.step = 3;
            break;
          case 402:
            this.$userInvalid();
            break;
          case 404:
            this.$userNotFound();
            break;
          case 406:
            this.$message.warning("您已提交过认领申请！");
            break;
        }
      })
      .catch(err => {
        console.log(err);
      })
    },
    isStep1Valid() {
      return !(this.applyInfo.author_name === '' || this.applyInfo.affiliation_name === ''
          || this.applyInfo.work_email === '' || this.applyInfo.fields === '');
    },
    isStep2Valid() {
      for (let i = 0; i < this.papers_group_state.length; i++) {
        if (this.papers_group_state[i].selected === true) {
          this.applyInfo.author_id = this.papers_group_state[i].author_id;
          return true;
        }
      }
      return false;
    },
    gotoHome() {
      this.$router.push('/');
    },
    gotoArticle(paper_id) {
      let routeUrl = this.$router.resolve({
        path: '/article',
        query: { v: paper_id }
      });
      window.open(routeUrl .href, "_blank");
    },
    getArticlesByAuthor() {
      if (this.authors.length >= this.author_count) {
        this.loadMoreDisable = true;
        return;
      }

      let author_name = this.applyInfo.author_name;

      let _loadingIns;
      if (this.step === 1)
        _loadingIns = this.$loading({fullscreen: true, text: '正在根据您的姓名获取文献组'});
      this.$axios({
        method: 'post',
        url: '/submit/get/papers/',
        data: qs.stringify({
          author_name: author_name,
          page: this.author_page_idx,
          size: 6
        })
      })
      .then(res => {
        if (this.step === 1) _loadingIns.close();
        switch (res.data.status) {
          case 200:
            this.authors = this.authors.concat(res.data.authors);
            this.author_page_idx += 1;
            this.author_count = res.data.author_count;
            if (this.authors.length >= this.author_count)
              this.loadMoreDisable = true;
            this.step = 2;
            // Init Selected
            this.papers_group_state = [];
            for (var i = 0; i < this.authors.length; i++) {
              this.papers_group_state.push({
                open: false,
                selected: false,
                author_id: this.authors[i].author_id
              })
            }
            this.papers_group_state[0].open = true;
            break;
        }
      })
      .catch(err => {
        console.log(err);
      })
    }
  },
}
</script>

<style scoped>
@import "../../styles/article.css";

.buttons{
  position: relative;
  margin: auto;
  left: 8%;
}
.button11{
  /* position: relative;
  margin: auto;
  left: 10%; */
  text-align: center;
}
.grid-content{
  position: relative;
  margin: auto;
  left: 17%;
  width: 100%;
  /* text-align: center; */
}
.block1{
 padding-left: 0px;
}
.block2{
  padding-left: 100px;
}
.block3{

}
.apply-settle .info-div {
  min-height: 500px;
  background-color: white;
  padding-top: 25px;
  padding-left: 45px;
  padding-bottom: 25px;
  margin-left: 170px;
  margin-top: 40px;
  width: 80%;
  text-align: left;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .08), 0 0 6px rgba(0, 0, 0, .04)
}

.apply-settle .sub-title {
  font-size: 17px;
  font-weight: 600;
  margin-top: 4px;
  color:black
}

.fill-in-row {
  padding: 10px;
  margin-bottom: 5px;
}


.article-blocks .article-item {
  margin-top: 20px;
  display: flex;
}

.article-blocks .article-item >>> .el-card__body {
  width: 100%;
  padding: 25px 30px 15px;
}

.article-blocks .article-item >>> .el-divider--horizontal {
  margin: 10px 0;
}

.choose-paper-checkbox >>> .el-checkbox__inner {
  width: 20px;
  height: 20px;
}

.choose-paper-checkbox >>> .el-checkbox__inner::after {

  height: 12px;
  left: 7px;
}


.choose-paper-checkbox >>> .el-checkbox__inner {
  width: 20px;
  height: 20px;
}


</style>